package com.lesports.qmt.cms.web.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.lesports.LeConstants;
import com.lesports.api.common.PageParam;
import com.lesports.qmt.cms.api.common.PageType;
import com.lesports.qmt.cms.api.dto.TColumn;
import com.lesports.qmt.cms.api.dto.TColumnPage;
import com.lesports.qmt.cms.api.dto.TWidget;
import com.lesports.qmt.cms.client.QmtCmsApis;
import com.lesports.qmt.resource.ComboResourceCreaters;
import com.lesports.qmt.resource.core.ComboResource;
import com.lesports.spring.boot.exception.LeWebApplicationException;
import com.lesports.spring.boot.mvc.LeStatus;
import com.lesports.utils.PageUtils;
import com.lesports.utils.math.LeNumberUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiangbo
 * @since 2016.10.20
 */
@Controller
@RequestMapping(value = "/render")
public class ColumnPageController {

    private static final Logger LOG = LoggerFactory.getLogger(ColumnPageController.class);

    @RequestMapping(value = "/d/**", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String renderData(@RequestParam Map<String, Object> params, HttpServletRequest request,
                             Model model) {
        try {
            LOG.info("begin to render, params : {}", params);
            TColumnPage page = getColumnPage(params, request);
            if (page == null) {
                throw new LeWebApplicationException("illegal argument!!!!", LeStatus.BAD_REQUEST);
            }
            Map dataMap = JSON.parseObject(page.getData(), HashMap.class);
            //准备data数据
            prepareData(page, dataMap);
            model.addAllAttributes(dataMap);
            model.addAttribute("alld", dataMap);
            return "ddata";
        } catch (LeWebApplicationException e) {
            throw e;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new LeWebApplicationException(e.getMessage(), LeStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @RequestMapping(value = "/p/**", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String render(@RequestParam Map<String, Object> params, HttpServletRequest request,
                         Model model) {
        try {
            LOG.info("begin to render, params : {}", params);
            TColumnPage page = getColumnPage(params, request);
            if (page == null) {
                throw new LeWebApplicationException("illegal argument!!!!", LeStatus.BAD_REQUEST);
            }
            Map dataMap = JSON.parseObject(page.getData(), HashMap.class);
            //准备data数据
            prepareData(page, dataMap);
            model.addAllAttributes(dataMap);
            return String.valueOf(page.getId());
        } catch (LeWebApplicationException e) {
            throw e;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new LeWebApplicationException(e.getMessage(), LeStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private void prepareData(TColumnPage tPage, Map<String, Object> dataMap) {
        if (MapUtils.isEmpty(dataMap)) {
            return;
        }
        Map<String, String> widgetVersionMap = Maps.newHashMap();
        if(CollectionUtils.isNotEmpty(tPage.getWPaths())){
            for(String wPath : tPage.getWPaths()){
                String version = "1";
                TWidget widget = QmtCmsApis.getTWidgetByPath(wPath);
                if(widget != null){
                    version = widget.getVersion();
                }
                widgetVersionMap.put(wPath, version);
            }
        }
        dataMap.put("resVersion", widgetVersionMap);
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            String wName = entry.getKey();
            Map wData = (Map) entry.getValue();
            if (MapUtils.getIntValue(wData, "dataType") == 1) {
                long resourceId = MapUtils.getLongValue(wData, "rsId", -1);
                if(resourceId <= 0){
                    LOG.error("illegal resource for widget data. name : {}, data : {}", wName, wData);
                    continue;
                }
                PageParam pp = PageUtils.createPageParam(1, MapUtils.getIntValue(wData, "count", LeConstants.DEFAULT_PAGE_SIZE));
                ComboResource resource = ComboResourceCreaters.getComboResource(resourceId, pp, null);
                wData.put("data", resource);
            }
        }
    }

    private TColumnPage getColumnPage(Map<String, Object> params, HttpServletRequest request) {
        String typeValue = MapUtils.getString(params, "type", "PC");
        PageType type = PageType.valueOf(typeValue);
        if (type == null) {
            type = PageType.PC;
        }
        Long columnId = MapUtils.getLong(params, "columnId", null);
        TColumn column = null;
        if (columnId != null) {
            //优先处理columnId参数
            column = QmtCmsApis.getTColumnById(columnId);
        }
        if (column == null) {
            //处理path参数
            String path = MapUtils.getString(params, "path", null);
            if (StringUtils.isEmpty(path)) {
                //uri作为path
                path = request.getRequestURI();
            }
            column = QmtCmsApis.getTColumnByFullPath(path);
        }
        if (column == null) {
            throw new LeWebApplicationException("illegal argument!!!!", LeStatus.BAD_REQUEST);
        }
        return getColumnPageId(column, type);
    }

    private TColumnPage getColumnPageId(TColumn column, PageType type) {
        if (type == PageType.MOBILE) {
            return column.getMPage();
        }
        if (type == PageType.DUMMY){
            return column.getDummyPage();
        }
        return column.getPcPage();
    }


}
